"strict";
import "./index.scss";
import { useReducer, useEffect, useRef } from "react";
import { initChess, MyChess } from "./Chessman";
import { MyChessman } from "./class/Chessman";
import { Board } from "./Board";
import { initBoardChessman } from "./config";
import { cloneDeep } from "lodash";
import { stateReducer } from "./dispatch";

function ChineseChess({}) {
  const [state, dispatch] = useReducer(stateReducer, {
    checkedChessman: null,
    movePositionPaths: [],
    winner: "",
    round: "red",
    // 存活的棋子
    survivalChessman: [],
    chessmanDom: [],
    cache: [],
  });
  const dataFetchedRef = useRef(false);

  let over = true;
  let date;
  let openDate = performance.now();
  function chessClick(item, k) {
    if (state.winner) return;
    date = Date.now();
    if (item.camp !== state.round) return;
    const prevSurvivalChessman = cloneDeep(state.survivalChessman);
    over = false;
    dispatch({ type: "checked", key: item.key });
  }
  async function moveClick(e) {
    const initX = 248 - 22.5;
    const initY = 1111 - 22.5 + 36;
    const chessmanSize = 50;
    const moveX = Math.floor((e.pageX - initX) / chessmanSize);
    const moveY = Math.floor((e.pageY - initY) / chessmanSize);
    console.log(moveX, moveY, e.pageY, initY);
    if (state.checkedChessman === null) return;
    if (!over) return;
    date = Date.now() - openDate;
    dispatch({ type: "move", moveX, moveY });
  }

  function initPredictionPath(board) {
    for (let j = 0; j < board.children.length; j++) {
      const ele = board.children[j];
      ele.classList.remove("show");
    }
  }
  // function gameOver(camp) {
  //   console.log(camp);
  //   setState((prev) => {
  //     return {
  //       ...prev,
  //       winner: camp,
  //     };
  //   });
  // }
  async function reStart() {
    dispatch({ type: "init", dispatch });
  }

  // 悔棋
  function Reprev() {
    dispatch({ type: "backMove" });
  }

  useEffect(() => {
    // console.log(state && (await state));
  }, [state.survivalChessman]);

  useEffect(() => {
    if (dataFetchedRef.current) return;
    dataFetchedRef.current = true;
    console.log(123);
    reStart();
  }, []);

  return (
    <div className="chinese-chess" onClick={moveClick}>
      <button className="button-default" onClick={() => reStart()}>
        重开
      </button>
      <button className="button-default" onClick={() => Reprev()}>
        悔棋
      </button>
      <div className="chess-box">
        <Board />
        {Array.from(state.survivalChessman || []).map(
          ([key, item]: Array<MyChessman>) => (
            <MyChess
              key={item.key}
              chessName={item.chessName}
              x={item.x}
              y={item.y}
              camp={item.camp}
              isChecked={item.isChecked}
              onChessClick={() => chessClick(item, item.key)}
            ></MyChess>
          )
        )}
      </div>
    </div>
  );
}

export default ChineseChess;
